package com.wider.services.impl;

import com.wider.pojo.MinAndMax;
import com.wider.services.DataService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
 * @author Maple
 */
@Service
public class DataServiceImpl implements DataService {
    @Override
    public MinAndMax getMinAndMax(List<BigDecimal> valueList) {
        MinAndMax minAndMax = new MinAndMax();
        minAndMax.setMinValue(valueList.stream().filter(Objects::nonNull).min(BigDecimal::compareTo).orElse(new BigDecimal(0)));
        minAndMax.setMaxValue(valueList.stream().filter(Objects::nonNull).max(BigDecimal::compareTo).orElse(new BigDecimal(0)));
        return minAndMax;
    }

    @Override
    public BigDecimal getMeaningfulValues(MinAndMax minAndMax,BigDecimal referenceValue) {
        BigDecimal minValue = minAndMax.getMinValue();
        BigDecimal maxValue = minAndMax.getMaxValue();
        BigDecimal point1 = computing(maxValue, referenceValue);
        BigDecimal point2 = computing(minValue, referenceValue);
        if (point1.compareTo(point2)>0){
            return maxValue;
        }else {
            return minValue;
        }
    }

    public static BigDecimal computing(BigDecimal xRef, BigDecimal x){
        return x.subtract(xRef).abs();
    }

    @Override
    public BigDecimal  formulaCalculation(BigDecimal meaningfulValues, BigDecimal referenceValue){
        BigDecimal subtract = referenceValue.subtract(meaningfulValues);
        BigDecimal divide = subtract.divide(referenceValue,10,RoundingMode.HALF_UP);
        return divide;
    }

    @Override
    public BigDecimal findMedian(List<BigDecimal> valueList) {
        if (valueList == null || valueList.isEmpty()) {
            return null;
        }
        Collections.sort(valueList);
        int size = valueList.size();
        if (size % 2 == 1) {
            return valueList.get(size / 2);
        } else {
            BigDecimal middle1 = valueList.get(size / 2 - 1);
            BigDecimal middle2 = valueList.get(size / 2);
            return middle1.add(middle2).divide(BigDecimal.valueOf(2));
        }
    }
}
